/*
   Copyright (C) 2007 Yen-Ju Chen <yjchenx gmail>

   This application is free software; you can redistribute it and/or 
   modify it under the terms of the MIT license. See COPYING.

*/

#import "KRDataSource.h"

@implementation KRDataSource

- (NSObject <KRFactoryProtocol> *) factoryForGroup: (OKGroup *) group
{
	NSEnumerator *e = [collections objectEnumerator];
	NSObject <KRFactoryProtocol> *factory = nil;
	while ((factory = [e nextObject]))
	{
		OKGroup *rootGroup = [factory rootGroup];
		if ([rootGroup isEqual: group] ||
		    [[rootGroup allGroups] containsObject: group])
		{
			return factory;
		}
	}
//	NSLog(@"Internal Error: cannot find factory for group %@", group);
	return nil;
}

- (NSArray *) factories
{
	return collections;
}

/* NSObject */
- (id) init
{
	self = [super init];

	collections = [[NSMutableArray alloc] init];

	/* Find all collection */
	BKPluginRegistry *pluginRegistry = [BKPluginRegistry sharedInstance];
	NSEnumerator *enumerator = [[pluginRegistry loadedValidOrderedExtensionsFor:@"org.etoile-project.koelr.datasource.factory" protocol:@protocol(KRFactoryProtocol)] objectEnumerator];
	BKExtension *each;

	while ((each = [enumerator nextObject])) 
	{
		NSObject <KRFactoryProtocol> *collection = [each extensionInstance];
		if (collection == nil)
		{
			/* For some reason, bundle decide not to be used.
			   We skip it */
			continue;
		}
        [collections addObject: collection];
        DESTROY(collection);
    }
	
	return self;
}

- (void) dealloc
{
	DESTROY(collections);
	[super dealloc];
}

@end

